from uuid import uuid4
import json
import os
from datetime import datetime
from django.db.models import Q

from rest_framework import serializers

from .models import *
from apps import redis_client
from apps.products.models import ProductModel
from apps.publish.models import *
from apps.devices.models import DevicesModel
from apps.orderproducts.models import ProductOrderModel
from util.exception import ValidationError
from util.svn_tool import SvnExport
from django.conf import settings


class OrderCheckSerializer(serializers.ModelSerializer):
    order_id = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_name = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_name_number = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_company_number = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_company = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_phone = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    start_date = serializers.DateTimeField(allow_null=True)
    end_date = serializers.DateTimeField(allow_null=True)

    class Meta:
        model = OrderModel
        fields = ["order_id", "custom_name", "custom_name_number", "custom_company_number",
                  "custom_company", "custom_phone", "start_date", "end_date"]


#
class OrderListSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderModel
        fields = ["id", "order_id", "order_date", "custom_name", "custom_name_number", "custom_company_number",
                  "custom_company", "custom_phone"]


class orderCheckSerializer(serializers.ModelSerializer):
    order_id = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    order_date = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_name = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_name_number = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_company_number = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_company = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_phone = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    products = serializers.ListField(allow_null=True, allow_empty=True)

    class Meta:
        model = OrderModel
        fields = ["order_id", "order_date", "custom_name", "custom_name_number", "custom_company_number",
                  "custom_company", "custom_phone", "products"]

    def __format_date(self, order_date):
        datas = order_date.split("/")
        year = int(datas[0])
        month = int(datas[1])
        day = int(datas[2])
        d = datetime(year=year, month=month, day=day)
        return d

    def create(self, data):
        id = str(uuid4()).replace("-", "")
        s_data = {}
        s_data["id"] = id
        s_data["order_id"] = data["order_id"]
        s_data["order_date"] = self.__format_date(data["order_date"])
        s_data["custom_name"] = data["custom_name"]
        s_data["custom_name_number"] = data["custom_name_number"]
        s_data["custom_company_number"] = data["custom_company_number"]
        s_data["custom_company"] = data["custom_company"]
        s_data["custom_phone"] = data["custom_phone"]
        items = data.pop("products")
        items = self.cut_use_item(items)
        if not items:
            raise ValidationError(30002)
        order = OrderModel.objects.filter(order_id=s_data["order_id"]).first()
        if order:
            order_key = order.id
            order_id = s_data.pop("order_id")
            s_data.pop("id")
            s_data.update({
                "update_date": now()
            })
            OrderModel.objects.filter(id=order.id).update(**s_data)
        else:
            order_key = id
            order_id = s_data.get("order_id")
            OrderModel.objects.create(**s_data)
        self.create_product(items, order_key, order_id)

    def cut_use_item(self, items):
        use_item = []
        for item in items:
            id = str(uuid4()).replace("-", "")
            product_number = item.get("product_number")
            if product_number.startswith("CP"):
                use_item.append({
                    "product_number": item.get("product_number"),
                    "product_name": item.get("product_name"),
                    "product_sum": item.get("product_sum"),
                    "key": id
                })
        return use_item

    def create_product(self, items, order_key, order_id):
        for item in items:
            id = str(uuid4()).replace("-", "")
            product_number = item.get("product_number")
            product_sum = item.get("product_sum")
            p = ProductModel.objects.filter(product_number=product_number).first()
            if not p:
                ProductModel.objects.create(
                    **{"id": id, "product_number": item.get("product_number"),
                       "product_name": item.get("product_name")})
            self.orderproductcreate(product_number, product_sum, order_key, order_id)

    def orderproductcreate(self, product_number, product_sum, order_key, order_id):
        product = ProductModel.objects.filter(product_number=product_number).first()
        if product:
            orderproduct = ProductOrderModel.objects.filter(product_number=product_number).first()
            if orderproduct:
                orderproduct.product_sum = product_sum
                o_p_id = orderproduct.id
                orderproduct.save()
            else:
                product_key = product.id
                product_name = product.product_name
                id = str(uuid4()).replace("-", "")
                o_p_id = id
                data = {
                    "id": id,
                    "order_key": order_key,
                    "order_id": order_id,
                    "product_key": product_key,
                    "product_name": product_name,
                    "product_number": product_number,
                    "product_sum": product_sum
                }
                ProductOrderModel.objects.create(**data)
            p = ProductOrderModel.objects.filter(id=o_p_id).first()
            product_number = p.product_number
            product_name = p.product_name
            product_sum = p.product_sum
            order_id = p.order_id
            order_key = p.order_key
            ds = DevicesModel.objects.filter(product_number=product_number).all()
            ne_ad = product_sum - len(ds)
            if ne_ad <= 0:
                ne_ad = 0
            for i in range(ne_ad):
                id = str(uuid4()).replace("-", "")
                file_path = settings.CONFIG_PATH.format(order_id, id)
                data = {
                    "id": id,
                    "product_name": product_name,
                    "product_number": product_number,
                    "order_id": order_id,
                    "order_key": order_key,
                    "parameter_file_path": file_path
                }
                DevicesModel.objects.create(**data)
        else:
            raise ValidationError(20001)



class orderCreateSerializer(serializers.ModelSerializer):
    order_id = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    order_date = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_name = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_name_number = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_company_number = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_company = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_phone = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)

    class Meta:
        model = OrderModel
        fields = ["order_id", "order_date", "custom_name", "custom_name_number", "custom_company_number",
                  "custom_company", "custom_phone"]

    def __format_date(self, order_date):
        datas = order_date.split("-")
        year = int(datas[0])
        month = int(datas[1])
        day = int(datas[2])
        d = datetime(year=year, month=month, day=day)
        return d

    def create(self, data):
        id = str(uuid4()).replace("-", "")
        s_data = {}
        s_data["id"] = id
        s_data["order_id"] = data["order_id"]
        s_data["order_date"] = self.__format_date(data["order_date"])
        s_data["custom_name"] = data["custom_name"]
        s_data["custom_name_number"] = data["custom_name_number"]
        s_data["custom_company_number"] = data["custom_company_number"]
        s_data["custom_company"] = data["custom_company"]
        s_data["custom_phone"] = data["custom_phone"]
        order = OrderModel.objects.filter(order_id=s_data["order_id"]).first()
        if order:
            order_id = s_data.pop("order_id")
            s_data.update({
                "update_date": now()
            })
            OrderModel.objects.filter(id=order.id).update(**s_data)
        else:
            OrderModel.objects.create(**s_data)


class orderUpdateSerializer(serializers.ModelSerializer):
    id = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    order_id = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    order_date = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_name = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_name_number = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_company_number = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_company = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)
    custom_phone = serializers.CharField(max_length=50, allow_null=True, allow_blank=True)

    class Meta:
        model = OrderModel
        fields = ["id", "order_id", "custom_name", "custom_name_number", "custom_company_number",
                  "custom_company", "custom_phone", "order_date"]

    def update_order(self, data):
        s_data = {}
        s_data["order_id"] = data["order_id"]
        s_data["order_date"] = self.__format_date(data["order_date"])
        s_data["custom_name"] = data["custom_name"]
        s_data["custom_name_number"] = data["custom_name_number"]
        s_data["custom_company_number"] = data["custom_company_number"]
        s_data["custom_company"] = data["custom_company"]
        s_data["custom_phone"] = data["custom_phone"]
        OrderModel.objects.filter(id=data.get("id")).update(**data)

    def __format_date(self, order_date):
        order_date = order_date.split("T")[0]
        datas = order_date.split("-")
        year = int(datas[0])
        month = int(datas[1])
        day = int(datas[2])
        d = datetime(year=year, month=month, day=day)
        return d
